package com.ag.admin.security.support;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.springframework.stereotype.Service;

import com.ag.admin.security.SecurityManager;
import com.ag.bean.TbPermission;
import com.ag.bean.TbRole;
import com.ag.bean.TbRolePermission;

/**
 * 系统安全管理支持类
 * 
 * @author 黎肇明
 * 
 */
@Service("securityManager")
public class SecurityManagerSupport extends HibernateDaoSupport implements
		SecurityManager {

	@Autowired
	public void init(SessionFactory sessionFactory) {
		super.setSessionFactory(sessionFactory);
	}

	/**
	 * Servlet容器启动时载入系统全部角色与权限的映射
	 */
	@Override
	public Map<String, Map<String, TbPermission>> loadRoleAuthorities() {
		Map<String, Map<String, TbPermission>> roleMap = new HashMap<String, Map<String, TbPermission>>();
		String hsql = "select distinct r from TbRole r join fetch r.tbRolePermissions rp join fetch rp.tbPermission pmmm where pmmm.a = '0'";
		List<TbRole> roleList = getHibernateTemplate().find(hsql);
		for (TbRole tbRole : roleList) {
			Set<TbRolePermission> rpSet = tbRole.getTbRolePermissions();
			Map<String, TbPermission> pmsnMap = new HashMap<String, TbPermission>();
			for (Iterator<TbRolePermission> iterator = rpSet.iterator(); iterator
					.hasNext();) {
				TbRolePermission trp = (TbRolePermission) iterator.next();
				// System.out.println(tbRole.getRName()+":::"+trp.getTbPermission().getPName());
				pmsnMap.put(trp.getTbPermission().getPId(), trp
						.getTbPermission());
			}
			roleMap.put(tbRole.getRId(), pmsnMap);
		}
		/*
		 * for (String strMap : roleMap.keySet()) { Map<String, TbPermission>
		 * tm=roleMap.get(strMap); for (String t : tm.keySet()) {
		 * System.out.println("tm.get(t).getPName()"+tm.get(t).getPName()); } }
		 */
		return roleMap;
	}

}
